package com.huowei.htzy.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.huowei.htzy.R;
import com.huowei.htzy.adapter.GoodAdapter;
import com.huowei.htzy.adapter.HomeGridAdapter;
import com.huowei.htzy.adapter.ImageAdapter;
import com.huowei.htzy.adapter.NetworkImageHolderView;
import com.huowei.htzy.application.MyApplication;
import com.huowei.htzy.common.Constants;
import com.huowei.htzy.modle.Deadline;
import com.huowei.htzy.modle.Goods;
import com.huowei.htzy.modle.Home1;
import com.huowei.htzy.modle.Home6;
import com.huowei.htzy.modle.Home7;
import com.huowei.htzy.modle.Home8;
import com.huowei.htzy.modle.Item;
import com.huowei.htzy.util.GlideUtil;
import com.huowei.htzy.util.RequestInterface;
import com.huowei.htzy.util.RequestUtil;
import com.huowei.htzy.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements RequestInterface, OnItemClickListener, View.OnClickListener {


    @InjectView(R.id.dian)
    LinearLayout dian;
    @InjectView(R.id.home_convenient)
    ConvenientBanner homeConvenient;
    private List<Item> itemList = new ArrayList<>();
    @InjectView(R.id.hf_search)
    LinearLayout hfSearch;
    @InjectView(R.id.hf_scan)
    Button hfScan;
    @InjectView(R.id.iv_category_1)
    ImageView ivCategory1;
    @InjectView(R.id.iv_category_2)
    ImageView ivCategory2;
    @InjectView(R.id.iv_category_3)
    ImageView ivCategory3;
    @InjectView(R.id.iv_category_4)
    ImageView ivCategory4;
    @InjectView(R.id.iv_category_5)
    ImageView ivCategory5;
    @InjectView(R.id.tableRow1)
    TableRow tableRow1;
    private List<View> views = new ArrayList<>();
    private List<Home1> home1s = new ArrayList<>();
    private List<Home7> home7s = new ArrayList<>();
    private List<String> trademarkImageList = new ArrayList<>();
    private static String FILENAME = "json.txt";
    private List<String> lineImageList = new ArrayList<>();
    private Deadline deadline;
    private Home6 home6;
    private Home8 home8;
    private Goods goods;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.inject(this, view);
        //初始化view
        initView();
        //判断网络是否连接
        boolean networkAvailable = MyApplication.isConnected(getActivity());
        if (networkAvailable){
            //请求数据
            RequestData();
        }else{
            Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();
            readJson();
        }
        return view;
    }

    private void initView() {
        hfSearch.setOnClickListener(this);
        hfScan.setOnClickListener(this);
        ivCategory1.setOnClickListener(this);
        ivCategory2.setOnClickListener(this);
        ivCategory3.setOnClickListener(this);
        ivCategory4.setOnClickListener(this);
    }

    private void setVpData() {
        views.clear();
        dian.removeAllViews();
        for (int i = 0; i < itemList.size(); i++) {
            //广告图显示区域下方 红色表示区域
            ImageView dianimageView = new ImageView(HomeFragment.this.getActivity());
            ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1);
            dianimageView.setLayoutParams(params);
            dianimageView.setBackgroundResource(R.drawable.dian_select);
            dian.addView(dianimageView);
            views.add(dianimageView);
        }
        //设置第一个图标为选中
        ImageView iv = (ImageView) views.get(0);
        iv.setSelected(true);
        homeConvenient.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, itemList)    //设置需要切换的View
                .setPointViewVisible(true)    //设置指示器是否可见
//                .setPageIndicator(new int[]{R.mipmap.android_activities_bg, R.mipmap.android_activities_cur})   //设置指示器圆点
                .startTurning(2000);     //设置自动切换（同时设置了切换时间间隔）
//                .stopTurning();    //关闭自动切换
        homeConvenient.setManualPageable(true);  //设置手动影响（设置了该项无法手动切换）
        homeConvenient.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);//设置指示器位置（左、中、右）
        homeConvenient.setOnItemClickListener(this); //设置点击监听事件
        //设置翻页的效果，不需要翻页效果可用不设
//        myConvenientBanner.setPageTransformer(Transformer.DefaultTransformer);
        homeConvenient.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < views.size(); i++) {
                    ImageView iv = (ImageView) views.get(i);
                    if (i == position) {
                        iv.setSelected(true);
                    } else {
                        iv.setSelected(false);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void RequestData() {
        RequestUtil util = new RequestUtil(getActivity(), this);
        util.getRequest(Constants.URL_HOME);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onSuccess(String jsonStr) {
        if (jsonStr == null){
            Toast.makeText(getActivity(), "当前网络不佳！", Toast.LENGTH_SHORT).show();
            readJson();
        }else {
            //存储到本地
            FileOutputStream out = null;
            try {
                out = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
                out.write(jsonStr.getBytes("UTF-8"));
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //解析数据
            parseJson(jsonStr);
        }
    }

    private void parseJson(String jsonStr) {
        home6 = null;
        home8 = null;
        lineImageList.clear();
        trademarkImageList.clear();
        itemList.clear();
        home1s.clear();
        home7s.clear();
        try {
            //解析数据
            Gson gson = new Gson();
            JSONObject jsonObject = new JSONObject(jsonStr);
            int code = jsonObject.getInt("code");
            if (code == 200) {
                JSONArray jsonArray = jsonObject.getJSONArray("datas");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject advObject = jsonArray.getJSONObject(i);
                    if (advObject.has("adv_list")) {
                        JSONObject advListObject = advObject.getJSONObject("adv_list");
                        JSONArray items = advListObject.getJSONArray("item");
                        for (int j = 0; j < items.length(); j++) {
                            JSONObject itemsJSONObject = items.getJSONObject(j);
                            String data = itemsJSONObject.getString("data");
                            String image = itemsJSONObject.getString("image");
                            String type = itemsJSONObject.getString("type");
                            Item item = new Item(data, image, type);
                            itemList.add(item);
                        }
                    } else if (advObject.has("home1")) {
                        JSONObject advListObject = advObject.getJSONObject("home1");
                        Home1 home1 = gson.fromJson(advListObject.toString(), Home1.class);
                        home1s.add(home1);
                    } else if (advObject.has("deadline")) {
                        JSONObject advListObject = advObject.getJSONObject("deadline");
                        deadline = gson.fromJson(advListObject.toString(), Deadline.class);
                    } else if (advObject.has("home7")) {
                        JSONObject advListObject = advObject.getJSONObject("home7");
                        JSONArray itemArray = advListObject.getJSONArray("item");
                        for (int j = 0; j < itemArray.length(); j++) {
                            JSONObject itemObject = itemArray.getJSONObject(j);
                            Home7 home7 = gson.fromJson(itemObject.toString(), Home7.class);
                            home7s.add(home7);
                        }
                    } else if (advObject.has("home6")) {
                        JSONObject advListObject = advObject.getJSONObject("home6");
                        home6 = gson.fromJson(advListObject.toString(), Home6.class);
                        lineImageList.add(home6.getRectangle1_image());
                        lineImageList.add(home6.getRectangle2_image());
                    } else if (advObject.has("home8")) {
                        JSONObject advListObject = advObject.getJSONObject("home8");
                        home8 = gson.fromJson(advListObject.toString(), Home8.class);
                        trademarkImageList.add(home8.getRectangle1_image());
                        trademarkImageList.add(home8.getRectangle2_image());
                        trademarkImageList.add(home8.getRectangle3_image());
                        trademarkImageList.add(home8.getRectangle4_image());
                    }else if (advObject.has("goods")) {
                        JSONObject advListObject = advObject.getJSONObject("goods");
                        goods = gson.fromJson(advListObject.toString(), Goods.class);
                        System.out.println(goods.getTitle()+"*********-----------");
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //设置ViewPager滑动
        setVpData();
        //设置新品推荐
        setNewRecommend();
        //设置限时折扣
        setDeadLine();
        //设置推荐品牌
        setTrademark();
        //设置热销商品
        setHotSellGoods();
    }

    private void setHotSellGoods() {
        View hotHome = view.findViewById(R.id.include_home_hot);
        TextView hotText = (TextView) hotHome.findViewById(R.id.home_hot_title);
        ImageView hotImage = (ImageView) hotHome.findViewById(R.id.home_hot_title_image);
        MyGridView hotGridView = (MyGridView) hotHome.findViewById(R.id.home_hot_grid_view);
        hotText.setText(goods.getTitle());
        hotImage.setImageResource(R.mipmap.ic_home_selling);
        List<Goods.ItemBean> items = goods.getItem();
        hotGridView.setNumColumns(2);
        GoodAdapter gridAdapter = new GoodAdapter(items, getActivity());
        hotGridView.setAdapter(gridAdapter);
    }

    private void setTrademark() {
        for (int i = 0; i < home1s.size(); i++) {
            Home1 home1 = home1s.get(i);
            if (home1.getTitle().equals("推荐品牌")) {
                //设置品牌的数据
                showTrademark(home1);
            }
        }
    }

    private void showTrademark(Home1 home1) {
        View trademarkHome = view.findViewById(R.id.include_home_trademark);
        TextView trademarkText = (TextView) trademarkHome.findViewById(R.id.home_title);
        ImageView trademarkHead = (ImageView) trademarkHome.findViewById(R.id.home_title_head);
        ImageView trademarkImage = (ImageView) trademarkHome.findViewById(R.id.home_title_image);
        GridView trademarkGridView = (GridView) trademarkHome.findViewById(R.id.home_grid_view);
        trademarkText.setText(home1.getTitle());
        trademarkImage.setImageResource(R.mipmap.ic_home_brand);
        GlideUtil.setRequest(getActivity(),home1.getImage(),trademarkHead);
        trademarkGridView.setNumColumns(4);
        ImageAdapter imageAdapter = new ImageAdapter(trademarkImageList,getActivity());
        trademarkGridView.setAdapter(imageAdapter);
    }

    private void setDeadLine() {

        View lineHome = view.findViewById(R.id.include_home_line);
        TextView lineText = (TextView) lineHome.findViewById(R.id.home_title);
        ImageView lineHead = (ImageView) lineHome.findViewById(R.id.home_title_head);
        ImageView lineImage = (ImageView) lineHome.findViewById(R.id.home_title_image);
        GridView lineGridView = (GridView) lineHome.findViewById(R.id.home_grid_view);
        lineText.setText(deadline.getTitle());
        lineImage.setImageResource(R.mipmap.ic_home_time);
        GlideUtil.setRequest(getActivity(),deadline.getImage(),lineHead);
        lineGridView.setNumColumns(2);
        ImageAdapter imageAdapter = new ImageAdapter(lineImageList,getActivity());
        lineGridView.setAdapter(imageAdapter);
    }

    private void setNewRecommend() {
        for (int i = 0; i < home1s.size(); i++) {
            Home1 home1 = home1s.get(i);
            if (home1.getTitle().equals("新品推荐")) {
                //设置新品的数据
                showNewRecommend(home1);
            }
        }
    }

    private void showNewRecommend(Home1 home1) {
        View newHome = view.findViewById(R.id.include_home_new);
        TextView newText = (TextView) newHome.findViewById(R.id.home_title);
        ImageView newHead = (ImageView) newHome.findViewById(R.id.home_title_head);
        ImageView newImage = (ImageView) newHome.findViewById(R.id.home_title_image);
        GridView newGridView = (GridView) newHome.findViewById(R.id.home_grid_view);
        newText.setText(home1.getTitle());
        newImage.setImageResource(R.mipmap.ic_home_new);
        GlideUtil.setRequest(getActivity(),home1.getImage(),newHead);
        newGridView.setNumColumns(3);
        HomeGridAdapter gridAdapter = new HomeGridAdapter(home7s, getActivity());
        newGridView.setAdapter(gridAdapter);
    }

    @Override
    public void onError(VolleyError error) {
        Toast.makeText(getActivity(), "请求失败！", Toast.LENGTH_SHORT).show();
        readJson();
    }

    private void readJson() {
        FileInputStream in = null;
        ByteArrayOutputStream bout = null;
        try {
            byte[]buf = new byte[1024];
            bout = new ByteArrayOutputStream();
            int length = 0;
            in = getActivity().openFileInput(FILENAME); //获得输入流
            while((length=in.read(buf))!=-1){
                bout.write(buf,0,length);
            }
            byte[] content = bout.toByteArray();
            String fileJson = new String(content, "UTF-8");
            parseJson(fileJson);
            in.close();
            bout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //当前条目点击事件
    @Override
    public void onItemClick(int position) {
    }

    /**
     * 点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.hf_scan:
                //扫描操作
                IntentIntegrator integrator = new IntentIntegrator(getActivity());
                integrator.initiateScan();
                break;
            case R.id.hf_search:
                

                break;
            case R.id.iv_category_1:

                break;
            case R.id.iv_category_2:

                break;
            case R.id.iv_category_3:

                break;
            case R.id.iv_category_4:

                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            System.out.println(result+"------------------------");
            Toast.makeText(getActivity(),result, Toast.LENGTH_LONG).show();
        }
    }
}
